package com.yitongmao.core.network.httpclient;


import android.app.BuildConfig;

import java.io.IOException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 缓存没使用okhttp的缓存，把缓存现在放到外边
 */
public class OkHttpClientFactory {
    private static final Object LOCK = new Object();

    /*连接超时15秒,改成10秒
      读取超时20秒,改成10秒
      写入无超时(2000秒)，暂时改成20秒,改成10秒*/
    public static final int DEFAULT_CONNECT_TIMEOUT_MILLIS = 10000;
    public static final int DEFAULT_READ_TIMEOUT_MILLIS = 10000;
    public static final int DEFAULT_WRITE_TIMEOUT_MILLIS = 10000;

    private static OkHttpClient mOkHttpClient;
    private static OkHttpLogInterceptor logging;

    public static OkHttpClient getClient() {
        synchronized (LOCK) {
            if (mOkHttpClient == null) {
                mOkHttpClient = new OkHttpClient();
                if (BuildConfig.DEBUG && logging == null) {
                    logging = new OkHttpLogInterceptor();
                    logging.setLevel(OkHttpLogInterceptor.Level.BODY);
                }
                mOkHttpClient.newBuilder().connectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
                        .readTimeout(DEFAULT_READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
                        .writeTimeout(DEFAULT_WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS).build();

                if (BuildConfig.DEBUG && logging != null) {
                    // mOkHttpClient = mOkHttpClient.newBuilder().addInterceptor(logging).addInterceptor(new GzipResponseInterceptor()).build();
                    mOkHttpClient = mOkHttpClient.newBuilder().addInterceptor(logging).build();
                }
                // setCookieHandler();
            }
        }
        return mOkHttpClient;
    }

    public static OkHttpClient getClient(final HashMap headers) {

        if (headers != null) {
            synchronized (LOCK) {
                if (mOkHttpClient == null) {

                    if (BuildConfig.DEBUG && logging == null) {
                        logging = new OkHttpLogInterceptor();
                        logging.setLevel(OkHttpLogInterceptor.Level.BODY);
                    }

                    mOkHttpClient = new OkHttpClient();
                    mOkHttpClient.newBuilder()
                            .connectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
                            .readTimeout(DEFAULT_READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
                            .writeTimeout(DEFAULT_WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
                    mOkHttpClient.interceptors().clear();
                    mOkHttpClient.interceptors().add(new Interceptor() {
                        @Override
                        public Response intercept(Chain chain) throws IOException {
                            Request original = chain.request();

                            Request.Builder requestBuilder = original.newBuilder()
                                    .method(original.method(), original.body());
                            Iterator iter = headers.entrySet().iterator();
                            while (iter.hasNext()) {
                                Map.Entry entry = (Map.Entry) iter.next();
                                Object key = entry.getKey();
                                Object val = entry.getValue();
                                requestBuilder.addHeader(key.toString(), val.toString());
                            }
                            Request request = requestBuilder.build();
                            return chain.proceed(request);

                        }
                    });
                    if (BuildConfig.DEBUG) {
                        // mOkHttpClient = mOkHttpClient.newBuilder().addInterceptor(logging).addInterceptor(new GzipResponseInterceptor()).build();
                        mOkHttpClient = mOkHttpClient.newBuilder().addInterceptor(logging).build();
                    }
                    //setCookieHandler();
                }
            }
            return mOkHttpClient;
        } else {
            return getClient();
        }
    }

    public static boolean isEmptry(CharSequence str) {
        return str == null || str.length() == 0 || "null".equalsIgnoreCase(str.toString());

    }

    private static void setCookieHandler() {
        synchronized (LOCK) {
            CookieManager cookieManager = new CookieManager();
            cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
            CookieHandler.setDefault(cookieManager);
            //  mOkHttpClient.setCookieHandler(cookieManager);
        }
    }
}
